﻿using System.Linq;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

namespace WinRTControl
{
    public class PullBottomToRefreshPanel : Control
    {
        private ScrollViewer _containerScrollViewer;

        public event RoutedEventHandler ScrollBottomPushed;

        public PullBottomToRefreshPanel()
        {
            this.DefaultStyleKey = typeof(PullBottomToRefreshPanel);
            this.LayoutUpdated += OnLayoutUpdate;
        }

        void OnLayoutUpdate(object sender, object e)
        {
            this.LayoutUpdated -= OnLayoutUpdate;
            
            GridView gridView = this.Parent.Descendents().OfType<GridView>().FirstOrDefault();
            ListView listView = this.Parent.Descendents().OfType<ListView>().FirstOrDefault();
            if (gridView != null && gridView.Visibility == Visibility.Visible)
            {
                _containerScrollViewer = gridView.Descendents().OfType<ScrollViewer>().FirstOrDefault();
            }
            else if (listView != null && listView.Visibility == Visibility.Visible)
            {
                _containerScrollViewer = listView.Descendents().OfType<ScrollViewer>().FirstOrDefault();
            }
            if (_containerScrollViewer != null)
            {
                _containerScrollViewer.ViewChanged += OnViewChanged;
            }
        }

        void OnViewChanged(object sender, ScrollViewerViewChangedEventArgs e)
        {
            //TODO 这个地方可做延伸动画
            //Debug.WriteLine("HorizontalOffset---->" + _containerScrollViewer.HorizontalOffset);
            //Debug.WriteLine("ScrollableWidth---->" + this._containerScrollViewer.ScrollableWidth);
            if (_containerScrollViewer.HorizontalOffset > this._containerScrollViewer.ScrollableWidth - 0.1)
            {
                //Debug.WriteLine("event calling--->");
                RoutedEventHandler hanlder = this.ScrollBottomPushed;
                if (hanlder != null)
                {
                    hanlder(this, new RoutedEventArgs()); 
                }
            }
        }
    }
}
